# 创建系统管理页面
<template>
  <div class="system-management">
    <!-- 系统状态概览 -->
    <el-row :gutter="20" class="status-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>系统运行状态</span>
              <el-tag :type="getSystemStatusType(systemStatus.status)">
                {{ getSystemStatusLabel(systemStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">运行时长</span>
              <span class="value">{{ formatUptime(systemStatus.uptime) }}</span>
            </div>
            <div class="status-item">
              <span class="label">CPU使用率</span>
              <el-progress
                :percentage="systemStatus.cpuUsage"
                :status="getResourceStatus(systemStatus.cpuUsage)"
              />
            </div>
            <div class="status-item">
              <span class="label">内存使用率</span>
              <el-progress
                :percentage="systemStatus.memoryUsage"
                :status="getResourceStatus(systemStatus.memoryUsage)"
              />
            </div>
            <div class="status-item">
              <span class="label">磁盘使用率</span>
              <el-progress
                :percentage="systemStatus.diskUsage"
                :status="getResourceStatus(systemStatus.diskUsage)"
              />
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>消息队列状态</span>
              <el-tag :type="getQueueStatusType(queueStatus.status)">
                {{ getQueueStatusLabel(queueStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">活跃队列数</span>
              <span class="value">{{ queueStatus.activeQueues }}</span>
            </div>
            <div class="status-item">
              <span class="label">消息积压数</span>
              <span class="value">{{ queueStatus.backlogCount }}</span>
            </div>
            <div class="status-item">
              <span class="label">消费延迟</span>
              <span class="value">{{ queueStatus.consumptionDelay }}ms</span>
            </div>
            <div class="status-item">
              <span class="label">消费者数量</span>
              <span class="value">{{ queueStatus.consumerCount }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>监控告警状态</span>
              <el-tag :type="getAlertStatusType(alertStatus.status)">
                {{ getAlertStatusLabel(alertStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">今日告警数</span>
              <span class="value">{{ alertStatus.todayAlerts }}</span>
            </div>
            <div class="status-item">
              <span class="label">未处理告警</span>
              <span class="value">{{ alertStatus.pendingAlerts }}</span>
            </div>
            <div class="status-item">
              <span class="label">平均响应时间</span>
              <span class="value">{{ alertStatus.avgResponseTime }}ms</span>
            </div>
            <div class="status-item">
              <span class="label">告警规则数</span>
              <span class="value">{{ alertStatus.ruleCount }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>系统集成状态</span>
              <el-tag :type="getIntegrationStatusType(integrationStatus.status)">
                {{ getIntegrationStatusLabel(integrationStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">集成系统数</span>
              <span class="value">{{ integrationStatus.systemCount }}</span>
            </div>
            <div class="status-item">
              <span class="label">正常连接数</span>
              <span class="value">{{ integrationStatus.normalConnections }}</span>
            </div>
            <div class="status-item">
              <span class="label">异常连接数</span>
              <span class="value">{{ integrationStatus.abnormalConnections }}</span>
            </div>
            <div class="status-item">
              <span class="label">同步任务数</span>
              <span class="value">{{ integrationStatus.syncTasks }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统配置管理 -->
    <el-card class="config-section" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>系统配置管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleSaveConfig">保存配置</el-button>
            <el-button @click="handleResetConfig">重置</el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeConfigTab">
        <!-- 基本配置 -->
        <el-tab-pane label="基本配置" name="basic">
          <el-form
            ref="basicConfigForm"
            :model="basicConfig"
            :rules="basicConfigRules"
            label-width="120px"
          >
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="basicConfig.systemName" />
            </el-form-item>
            <el-form-item label="系统描述" prop="description">
              <el-input
                v-model="basicConfig.description"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <el-form-item label="管理员邮箱" prop="adminEmail">
              <el-input v-model="basicConfig.adminEmail" />
            </el-form-item>
            <el-form-item label="系统时区" prop="timezone">
              <el-select v-model="basicConfig.timezone">
                <el-option label="UTC+8" value="Asia/Shanghai" />
                <el-option label="UTC" value="UTC" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 性能配置 -->
        <el-tab-pane label="性能配置" name="performance">
          <el-form
            ref="performanceConfigForm"
            :model="performanceConfig"
            :rules="performanceConfigRules"
            label-width="120px"
          >
            <el-form-item label="缓存大小" prop="cacheSize">
              <el-input-number
                v-model="performanceConfig.cacheSize"
                :min="100"
                :max="10000"
                :step="100"
              />
              <span class="unit">MB</span>
            </el-form-item>
            <el-form-item label="线程池大小" prop="threadPoolSize">
              <el-input-number
                v-model="performanceConfig.threadPoolSize"
                :min="1"
                :max="100"
              />
            </el-form-item>
            <el-form-item label="连接超时" prop="connectionTimeout">
              <el-input-number
                v-model="performanceConfig.connectionTimeout"
                :min="1000"
                :max="30000"
                :step="1000"
              />
              <span class="unit">ms</span>
            </el-form-item>
            <el-form-item label="请求超时" prop="requestTimeout">
              <el-input-number
                v-model="performanceConfig.requestTimeout"
                :min="1000"
                :max="60000"
                :step="1000"
              />
              <span class="unit">ms</span>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全配置 -->
        <el-tab-pane label="安全配置" name="security">
          <el-form
            ref="securityConfigForm"
            :model="securityConfig"
            :rules="securityConfigRules"
            label-width="120px"
          >
            <el-form-item label="密码策略" prop="passwordPolicy">
              <el-select v-model="securityConfig.passwordPolicy">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
            <el-form-item label="登录失败锁定" prop="loginLock">
              <el-switch v-model="securityConfig.loginLock" />
            </el-form-item>
            <el-form-item
              label="失败次数"
              prop="maxLoginAttempts"
              v-if="securityConfig.loginLock"
            >
              <el-input-number
                v-model="securityConfig.maxLoginAttempts"
                :min="3"
                :max="10"
              />
            </el-form-item>
            <el-form-item label="会话超时" prop="sessionTimeout">
              <el-input-number
                v-model="securityConfig.sessionTimeout"
                :min="30"
                :max="1440"
                :step="30"
              />
              <span class="unit">分钟</span>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 日志配置 -->
        <el-tab-pane label="日志配置" name="logging">
          <el-form
            ref="loggingConfigForm"
            :model="loggingConfig"
            :rules="loggingConfigRules"
            label-width="120px"
          >
            <el-form-item label="日志级别" prop="logLevel">
              <el-select v-model="loggingConfig.logLevel">
                <el-option label="DEBUG" value="debug" />
                <el-option label="INFO" value="info" />
                <el-option label="WARN" value="warn" />
                <el-option label="ERROR" value="error" />
              </el-select>
            </el-form-item>
            <el-form-item label="日志保留天数" prop="logRetentionDays">
              <el-input-number
                v-model="loggingConfig.logRetentionDays"
                :min="7"
                :max="365"
                :step="7"
              />
            </el-form-item>
            <el-form-item label="日志文件大小" prop="logFileSize">
              <el-input-number
                v-model="loggingConfig.logFileSize"
                :min="10"
                :max="1000"
                :step="10"
              />
              <span class="unit">MB</span>
            </el-form-item>
            <el-form-item label="异步日志" prop="asyncLogging">
              <el-switch v-model="loggingConfig.asyncLogging" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 系统日志 -->
    <el-card class="log-section" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>系统日志</span>
          <div class="header-operations">
            <el-input
              v-model="logSearch"
              placeholder="搜索日志"
              style="width: 200px"
              clearable
              @clear="handleLogSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleExportLogs">导出日志</el-button>
            <el-button @click="handleRefreshLogs">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="logList"
        border
        v-loading="logLoading"
        style="width: 100%"
      >
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLogLevelType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" width="120" />
        <el-table-column prop="message" label="日志内容" min-width="300" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewLogDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="logPage"
          v-model:page-size="logPageSize"
          :total="logTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleLogPageSizeChange"
          @current-change="handleLogPageChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="logDetailVisible"
      title="日志详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="时间">
          {{ formatDateTime(currentLog.timestamp) }}
        </el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag :type="getLogLevelType(currentLog.level)">
            {{ currentLog.level }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="模块">
          {{ currentLog.module }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人">
          {{ currentLog.operator }}
        </el-descriptions-item>
        <el-descriptions-item label="日志内容" :span="2">
          {{ currentLog.message }}
        </el-descriptions-item>
        <el-descriptions-item label="堆栈信息" :span="2" v-if="currentLog.stack">
          <pre class="stack-trace">{{ currentLog.stack }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="相关数据" :span="2" v-if="currentLog.data">
          <pre class="log-data">{{ JSON.stringify(currentLog.data, null, 2) }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  getSystemStatus,
  getQueueStatus,
  getAlertStatus,
  getIntegrationStatus,
  getSystemConfig,
  updateSystemConfig,
  getSystemLogs,
  exportSystemLogs
} from '@/api/message'

// 系统状态数据
const systemStatus = reactive({
  status: 'normal',
  uptime: 0,
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0
})

const queueStatus = reactive({
  status: 'normal',
  activeQueues: 0,
  backlogCount: 0,
  consumptionDelay: 0,
  consumerCount: 0
})

const alertStatus = reactive({
  status: 'normal',
  todayAlerts: 0,
  pendingAlerts: 0,
  avgResponseTime: 0,
  ruleCount: 0
})

const integrationStatus = reactive({
  status: 'normal',
  systemCount: 0,
  normalConnections: 0,
  abnormalConnections: 0,
  syncTasks: 0
})

// 配置表单数据
const activeConfigTab = ref('basic')
const basicConfig = reactive({
  systemName: '',
  description: '',
  adminEmail: '',
  timezone: 'Asia/Shanghai'
})

const performanceConfig = reactive({
  cacheSize: 1000,
  threadPoolSize: 10,
  connectionTimeout: 5000,
  requestTimeout: 30000
})

const securityConfig = reactive({
  passwordPolicy: 'medium',
  loginLock: true,
  maxLoginAttempts: 5,
  sessionTimeout: 30
})

const loggingConfig = reactive({
  logLevel: 'info',
  logRetentionDays: 30,
  logFileSize: 100,
  asyncLogging: true
})

// 表单验证规则
const basicConfigRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  adminEmail: [
    { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const performanceConfigRules = {
  cacheSize: [
    { required: true, message: '请输入缓存大小', trigger: 'blur' }
  ],
  threadPoolSize: [
    { required: true, message: '请输入线程池大小', trigger: 'blur' }
  ]
}

const securityConfigRules = {
  passwordPolicy: [
    { required: true, message: '请选择密码策略', trigger: 'change' }
  ],
  maxLoginAttempts: [
    { required: true, message: '请输入最大登录失败次数', trigger: 'blur' }
  ]
}

const loggingConfigRules = {
  logLevel: [
    { required: true, message: '请选择日志级别', trigger: 'change' }
  ],
  logRetentionDays: [
    { required: true, message: '请输入日志保留天数', trigger: 'blur' }
  ]
}

// 日志列表数据
const logList = ref([])
const logLoading = ref(false)
const logPage = ref(1)
const logPageSize = ref(20)
const logTotal = ref(0)
const logSearch = ref('')
const logDetailVisible = ref(false)
const currentLog = ref({})

// 初始化
onMounted(() => {
  loadSystemStatus()
  loadConfig()
  loadLogs()
  
  // 定时刷新状态
  const timer = setInterval(loadSystemStatus, 30000)
  
  onUnmounted(() => {
    clearInterval(timer)
  })
})

// 加载系统状态
const loadSystemStatus = async () => {
  try {
    const [systemRes, queueRes, alertRes, integrationRes] = await Promise.all([
      getSystemStatus(),
      getQueueStatus(),
      getAlertStatus(),
      getIntegrationStatus()
    ])
    
    Object.assign(systemStatus, systemRes.data)
    Object.assign(queueStatus, queueRes.data)
    Object.assign(alertStatus, alertRes.data)
    Object.assign(integrationStatus, integrationRes.data)
  } catch (error) {
    console.error('加载系统状态失败:', error)
    ElMessage.error('加载系统状态失败')
  }
}

// 加载系统配置
const loadConfig = async () => {
  try {
    const res = await getSystemConfig()
    const config = res.data
    
    Object.assign(basicConfig, config.basic)
    Object.assign(performanceConfig, config.performance)
    Object.assign(securityConfig, config.security)
    Object.assign(loggingConfig, config.logging)
  } catch (error) {
    console.error('加载系统配置失败:', error)
    ElMessage.error('加载系统配置失败')
  }
}

// 保存配置
const handleSaveConfig = async () => {
  try {
    const config = {
      basic: basicConfig,
      performance: performanceConfig,
      security: securityConfig,
      logging: loggingConfig
    }
    
    await updateSystemConfig(config)
    ElMessage.success('保存配置成功')
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  }
}

// 重置配置
const handleResetConfig = () => {
  ElMessageBox.confirm('确定要重置所有配置吗？', '提示', {
    type: 'warning'
  }).then(() => {
    loadConfig()
    ElMessage.success('重置配置成功')
  })
}

// 加载日志列表
const loadLogs = async () => {
  logLoading.value = true
  try {
    const res = await getSystemLogs({
      page: logPage.value,
      pageSize: logPageSize.value,
      search: logSearch.value
    })
    
    logList.value = res.data.list
    logTotal.value = res.data.total
  } catch (error) {
    console.error('加载日志失败:', error)
    ElMessage.error('加载日志失败')
  } finally {
    logLoading.value = false
  }
}

// 导出日志
const handleExportLogs = async () => {
  try {
    const res = await exportSystemLogs({
      search: logSearch.value
    })
    
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `系统日志_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  }
}

// 查看日志详情
const handleViewLogDetail = (row) => {
  currentLog.value = row
  logDetailVisible.value = true
}

// 工具方法
const getSystemStatusType = (status) => {
  const typeMap = {
    normal: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return typeMap[status] || 'info'
}

const getSystemStatusLabel = (status) => {
  const labelMap = {
    normal: '正常',
    warning: '警告',
    error: '异常'
  }
  return labelMap[status] || status
}

const getQueueStatusType = (status) => {
  const typeMap = {
    normal: 'success',
    busy: 'warning',
    blocked: 'danger'
  }
  return typeMap[status] || 'info'
}

const getQueueStatusLabel = (status) => {
  const labelMap = {
    normal: '正常',
    busy: '繁忙',
    blocked: '阻塞'
  }
  return labelMap[status] || status
}

const getAlertStatusType = (status) => {
  const typeMap = {
    normal: 'success',
    warning: 'warning',
    critical: 'danger'
  }
  return typeMap[status] || 'info'
}

const getAlertStatusLabel = (status) => {
  const labelMap = {
    normal: '正常',
    warning: '警告',
    critical: '严重'
  }
  return labelMap[status] || status
}

const getIntegrationStatusType = (status) => {
  const typeMap = {
    normal: 'success',
    partial: 'warning',
    error: 'danger'
  }
  return typeMap[status] || 'info'
}

const getIntegrationStatusLabel = (status) => {
  const labelMap = {
    normal: '正常',
    partial: '部分异常',
    error: '异常'
  }
  return labelMap[status] || status
}

const getResourceStatus = (value) => {
  if (value <= 60) return 'success'
  if (value <= 80) return 'warning'
  return 'exception'
}

const getLogLevelType = (level) => {
  const typeMap = {
    DEBUG: 'info',
    INFO: 'success',
    WARN: 'warning',
    ERROR: 'danger'
  }
  return typeMap[level] || 'info'
}

const formatUptime = (seconds) => {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  const parts = []
  if (days > 0) parts.push(`${days}天`)
  if (hours > 0) parts.push(`${hours}小时`)
  if (minutes > 0) parts.push(`${minutes}分钟`)
  
  return parts.join('') || '0分钟'
}

const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 事件处理
const handleLogSearch = () => {
  logPage.value = 1
  loadLogs()
}

const handleLogPageSizeChange = (val) => {
  logPageSize.value = val
  loadLogs()
}

const handleLogPageChange = (val) => {
  logPage.value = val
  loadLogs()
}

const handleRefreshLogs = () => {
  loadLogs()
}
</script>

<style lang="scss" scoped>
.system-management {
  padding: 20px;
  
  .status-overview {
    margin-bottom: 20px;
    
    .status-card {
      height: 100%;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .card-content {
        .status-item {
          margin-bottom: 15px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            display: block;
            margin-bottom: 5px;
            color: #909399;
          }
          
          .value {
            font-size: 16px;
            font-weight: bold;
          }
          
          .unit {
            margin-left: 5px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .config-section {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-operations {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
  
  .log-section {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-operations {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
    
    .stack-trace,
    .log-data {
      margin: 0;
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-family: monospace;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }
}
</style> 